package com.frog.common.util;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

public class RandomNumberUtil {


    /**
     * 从范围内获取1个数
     * @param startInclusive    起始值，包含
     * @param endExclusive      结束值，不包含
     * @return
     */
    public static int getRandomNumber(final int startInclusive, final int endExclusive) {
        return ThreadLocalRandom.current().nextInt(startInclusive, endExclusive);
    }

    // 根据 seed 在指定范围内生成一个随机数
    public static int getRandomNumber(long seed, int startInclusive, int endExclusive) {
        Random random = new Random(seed);
        return random.nextInt((endExclusive - startInclusive) + 1) + startInclusive;
    }

    /**
     * 从范围内获取N个数
     * @param startInclusive    起始值，包含
     * @param endExclusive      结束值，不包含
     * @param size              个数
     * @return
     */
    public static List<Integer> getRandomList(final int startInclusive, final int endExclusive, final int size){
        if(endExclusive<startInclusive){
            throw new IllegalArgumentException(String.format("Start value must be smaller or equal to end value."));
        }
        if(startInclusive < 0){
            throw new IllegalArgumentException(String.format("Both range values must be non-negative."));
        }
        int range = endExclusive-startInclusive;
        if(range < size<<1){
            List<Integer> list = new ArrayList<>(range);
            for(int i=startInclusive;i<endExclusive;i++){
                list.add(i);
            }
            while (true){
                if(list.size() <= size){
                    return list;
                }
                list.remove(ThreadLocalRandom.current().nextInt(0, list.size()));
            }
        }
        Set<Integer> set = new HashSet<>(size);
        while (true){
            if(set.size() == size){
                List<Integer> list = new ArrayList<>(set);
                Collections.sort(list);
                return list;
            }
            set.add(ThreadLocalRandom.current().nextInt(startInclusive, endExclusive));
        }
    }

}
